package club.xcgame520.picturepicker;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import club.xcgame520.picturepicker.bean.Picture;
import club.xcgame520.picturepicker.bean.PictureFolder;
import club.xcgame520.picturepicker.util.ScreenUtil;
import club.xcgame520.picturepicker.view.FolderWindow;
import club.xcgame520.picturepicker.view.GridSpacingItemDecoration;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PicturePickerActivity extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor>, FolderWindow.OnItemClickListener {

    public static final String TAG = "PicturePicker";

    private final static String[] IMAGE_PROJECTION = {
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATE_ADDED,
            MediaStore.Images.Media._ID};


    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;
    /**
     * 单选
     */
    public static final int MODE_SINGLE = 2;


    public static final String RESULT_MULTI_KEY = "pictureList";

    public static final String RESULT_SINGLE_KEY = "picture";

    private int mode;
    private int maxSelectNumber;

    private Toolbar tTitle;
    private TextView tvComplete;

    private RecyclerView rvContent;
    private RecyclerView.Adapter<?> adapter;

    private ArrayList<PictureFolder> pictureFolderList;
    private PictureFolder pictureFolder;

    private ArrayList<Picture> selectPictureList;

    private LinearLayout llClassify;
    private TextView tvClassify;
    private TextView tvPreview;

    private RelativeLayout rlOperation;
    private FolderWindow folderWindow;

    private File tempPictureFile;

    private String providerAuthority;

    /**
     * 启动图片多选
     *
     * @param activity
     * @param requestCode
     * @param maxSelectNumber 选择图片的最大数量 默认为9张
     */
    public static void startMultiSelector(Activity activity, int requestCode, int maxSelectNumber) {
        Intent intent = new Intent(activity, PicturePickerActivity.class);
        intent.putExtra("mode", MODE_MULTI);
        intent.putExtra("maxSelectNumber", maxSelectNumber);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动图片多选
     *
     * @param activity
     * @param requestCode
     * @param maxSelectNumber   选择图片的最大数量 默认为9张
     * @param selectPictureList 选择的图片的回填
     */
    public static void startMultiSelector(Activity activity, int requestCode, int maxSelectNumber, ArrayList<Picture> selectPictureList) {
        Intent intent = new Intent(activity, PicturePickerActivity.class);
        intent.putExtra("mode", MODE_MULTI);
        intent.putExtra("maxSelectNumber", maxSelectNumber);
        intent.putExtra("selectPictureList", selectPictureList);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * @param activity
     * @param requestCode
     */
    public static void startSingleSelector(Activity activity, String providerAuthority, int requestCode) {
        Intent intent = new Intent(activity, PicturePickerActivity.class);
        intent.putExtra("mode", MODE_SINGLE);
        intent.putExtra("providerAuthority", providerAuthority);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_picker);

        if (savedInstanceState == null) {

            mode = getIntent().getIntExtra("mode", MODE_MULTI);

            maxSelectNumber = getIntent().getIntExtra("maxSelectNumber", 9);

            if (getIntent().getSerializableExtra("selectPictureList") == null) {
                selectPictureList = new ArrayList<>();
            } else {
                selectPictureList = (ArrayList<Picture>) getIntent().getSerializableExtra("selectPictureList");
            }

            if (getIntent().getStringExtra("providerAuthority") == null) {
                providerAuthority = "";
            } else {
                providerAuthority = getIntent().getStringExtra("providerAuthority");
            }

        } else {

            tempPictureFile = (File) savedInstanceState.getSerializable("tempPictureFile");

            mode = savedInstanceState.getInt("mode", MODE_MULTI);

            maxSelectNumber = savedInstanceState.getInt("maxSelectNumber", 9);

            if (getIntent().getSerializableExtra("selectPictureList") == null) {
                selectPictureList = new ArrayList<>();
            } else {
                selectPictureList = (ArrayList<Picture>) savedInstanceState.getSerializable("selectPictureList");
            }

            if (savedInstanceState.getString("providerAuthority") == null) {
                providerAuthority = "";
            } else {
                providerAuthority = savedInstanceState.getString("providerAuthority");
            }

        }

        tTitle = findViewById(R.id.tTitle);
        setSupportActionBar(tTitle);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        tTitle.setNavigationIcon(R.drawable.vector_action_back);

        tvComplete = findViewById(R.id.tvComplete);
        tvComplete.setOnClickListener(this);

        rvContent = findViewById(R.id.rvContent);
        rvContent.setHasFixedSize(true);
        rvContent.addItemDecoration(new GridSpacingItemDecoration(3, ScreenUtil.dip2px(this, 2), false));
        rvContent.setLayoutManager(new GridLayoutManager(this, 3));

        rlOperation = findViewById(R.id.rlOperation);
        llClassify = findViewById(R.id.llClassify);
        llClassify.setOnClickListener(this);
        tvClassify = findViewById(R.id.tvClassify);
        tvPreview = findViewById(R.id.tvPreview);
        tvPreview.setOnClickListener(this);

        if (mode == MODE_MULTI) {
            tvPreview.setVisibility(View.VISIBLE);
            tvComplete.setVisibility(View.VISIBLE);
            adapter = new MultiPictureAdapter();
        }

        if (mode == MODE_SINGLE) {
            tvPreview.setVisibility(View.GONE);
            tvComplete.setVisibility(View.GONE);
            adapter = new SinglePictureAdapter();
        }
        rvContent.setAdapter(adapter);

        pictureFolderList = new ArrayList<>();
        getSupportLoaderManager().initLoader(1, null, this);

        folderWindow = new FolderWindow(this);
        folderWindow.setOnItemClickListener(this);

        int size = selectPictureList.size();
        if (size > 0) {
            tvComplete.setEnabled(true);
            tvPreview.setEnabled(true);
            tvComplete.setText("完成(" + size + "/" + maxSelectNumber + ")");
            tvPreview.setText("预览(" + size + ")");
        } else {
            tvComplete.setEnabled(false);
            tvPreview.setEnabled(false);
            tvComplete.setText("完成");
            tvPreview.setText("预览");
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putSerializable("tempPictureFile", tempPictureFile);
        outState.putInt("mode", mode);
        outState.putInt("maxSelectNumber", maxSelectNumber);
        outState.putString("providerAuthority", providerAuthority);
        outState.putSerializable("selectPictureList",selectPictureList);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llClassify) {
            if (folderWindow.isShowing()) {
                folderWindow.dismiss();
            } else {
                folderWindow.showAsDropDown(rlOperation);
            }
        }

        if (id == R.id.tvPreview) {
            Intent intent = new Intent(this, PicturePreviewActivity.class);
            intent.putExtra("pictureList", selectPictureList);
            intent.putExtra("selectPictureList", selectPictureList);
            intent.putExtra("maxSelectNumber", maxSelectNumber);
            intent.putExtra("currentShowIndex", 0);
            startActivityForResult(intent, 3);
        }

        if (id == R.id.tvComplete) {
            Intent intent = getIntent();
            intent.putExtra(RESULT_MULTI_KEY, selectPictureList);
            setResult(RESULT_OK, intent);
            finish();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {

            Picture picture = new Picture();
            picture.setPath(tempPictureFile.getPath());
            picture.setName(tempPictureFile.getName());
            picture.setDataTime(System.currentTimeMillis());
            try {
                ExifInterface exifInterface = new ExifInterface(tempPictureFile.getAbsolutePath());
                String createTime = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
                picture.setDataTime(simpleDateFormat.parse(createTime).getTime());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Intent intent = new Intent(this, PictureLookActivity.class);
            intent.putExtra("picture", picture);
            startActivityForResult(intent, 2);

        }

        // 单选
        if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
            Intent intent = getIntent();
            intent.putExtra(RESULT_SINGLE_KEY, data.getSerializableExtra("picture"));
            setResult(RESULT_OK, intent);
            finish();
        }

        if (requestCode == 3 && resultCode == RESULT_CANCELED && data != null) {

            selectPictureList = (ArrayList<Picture>) data.getSerializableExtra("selectPictureList");
            adapter.notifyDataSetChanged();

            int size = selectPictureList.size();
            if (size > 0) {
                tvComplete.setEnabled(true);
                tvPreview.setEnabled(true);
                tvComplete.setText("完成(" + size + "/" + maxSelectNumber + ")");
                tvPreview.setText("预览(" + size + ")");
            } else {
                tvComplete.setEnabled(false);
                tvPreview.setEnabled(false);
                tvComplete.setText("完成");
                tvPreview.setText("预览");
            }

        }

        if (requestCode == 3 && resultCode == RESULT_OK && data != null) {
            Intent intent = getIntent();
            intent.putExtra(RESULT_MULTI_KEY, data.getSerializableExtra("selectPictureList"));
            setResult(RESULT_OK, intent);
            finish();
        }

    }

    @NonNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {

        if (id == 1) {

            CursorLoader cursorLoader = new CursorLoader(
                    this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=?",
                    new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC");

            return cursorLoader;

        }

        return null;
    }

    @Override
    public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {

        if (loader.getId() == 1) {

            pictureFolderList.clear();

            PictureFolder allPictureFolder = new PictureFolder();
            allPictureFolder.setName("所有图片");
            allPictureFolder.setPath("/");

            if (data.getCount() > 0) {

                data.moveToFirst();

                do {

                    String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    // 如原图路径不存在或者路径存在但文件不存在,就结束当前循环
                    if (TextUtils.isEmpty(path) || !new File(path).exists()) {
                        continue;
                    }
                    String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                    long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));

                    Picture picture = new Picture(path, name, dateTime);

                    //分类的文件夹
                    PictureFolder classifyFolder = getPictureFolder(path, pictureFolderList);
                    classifyFolder.getPictureList().add(picture);

                    //全部图片的文件夹
                    allPictureFolder.getPictureList().add(picture);

                } while (data.moveToNext());

            }

            sortFolder(pictureFolderList);
            pictureFolderList.add(0, allPictureFolder);

            if (pictureFolder == null) {
                pictureFolder = pictureFolderList.get(0);
            } else {
                for (PictureFolder pf : pictureFolderList) {
                    if (tvClassify.getText().toString().equals(pf.getName())) {
                        pictureFolder = pf;
                    }
                }
            }
            folderWindow.bindData(pictureFolderList, pictureFolder);
            adapter.notifyDataSetChanged();

            Log.d("xiaocan", "当前显示PictureFolder：" + pictureFolder.toString());

        }

    }

    @Override
    public void onLoaderReset(@NonNull Loader<Cursor> loader) {

    }

    @Override
    public void onItemClick(int position) {
        pictureFolder = pictureFolderList.get(position);
        tvClassify.setText(pictureFolder.getName());
        adapter.notifyDataSetChanged();
    }

    private class SinglePictureAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        class CameraViewHolder extends RecyclerView.ViewHolder {

            LinearLayout llItem;

            public CameraViewHolder(View itemView) {
                super(itemView);

                llItem = itemView.findViewById(R.id.llItem);

            }
        }

        class PictureViewHolder extends RecyclerView.ViewHolder {

            ImageView ivPicture;

            public PictureViewHolder(View itemView) {
                super(itemView);

                ivPicture = itemView.findViewById(R.id.ivPicture);

            }
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            if (viewType == 1) {
                View itemView = LayoutInflater.from(PicturePickerActivity.this).inflate(R.layout.view_item_camera, parent, false);
                return new CameraViewHolder(itemView);
            }

            if (viewType == 2) {
                View itemView = LayoutInflater.from(PicturePickerActivity.this).inflate(R.layout.view_item_picture_single, parent, false);
                return new PictureViewHolder(itemView);
            }

            return null;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

            if (holder instanceof PictureViewHolder) {

                PictureViewHolder pictureViewHolder = (PictureViewHolder) holder;

                final Picture picture = pictureFolder.getPictureList().get(position - 1);
                Glide.with(PicturePickerActivity.this)
                        .load(picture.getPath()).apply(new RequestOptions()
                        .placeholder(R.mipmap.pp_placeholder)
                        .error(R.mipmap.pp_placeholder))
                        .into(pictureViewHolder.ivPicture);

                pictureViewHolder.ivPicture.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent(PicturePickerActivity.this, PictureLookActivity.class);
                        intent.putExtra("picture", picture);
                        startActivityForResult(intent, 2);

                    }
                });

            }

            if (holder instanceof CameraViewHolder) {
                CameraViewHolder cameraViewHolder = (CameraViewHolder) holder;
                cameraViewHolder.llItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (ContextCompat.checkSelfPermission(PicturePickerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                                ContextCompat.checkSelfPermission(PicturePickerActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                                ContextCompat.checkSelfPermission(PicturePickerActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        ) {

                            String state = Environment.getExternalStorageState();

                            if (state.equals(Environment.MEDIA_MOUNTED)) {

                                tempPictureFile = new File(getTargetDirPath(), "pp_" + System.currentTimeMillis() + ".jpg");
                                Log.d("临时文件保存路径：", tempPictureFile.getAbsolutePath());

                                //如果临时文件目录不存在，那就创建此文件目录
                                if (!tempPictureFile.exists()) {
                                    tempPictureFile.mkdirs();
                                    tempPictureFile.delete();
                                }

                                Intent intent = new Intent();
                                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(PicturePickerActivity.this, providerAuthority, tempPictureFile));
                                } else {
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempPictureFile));
                                }
                                startActivityForResult(intent, 1);

                            } else {
                                Toast.makeText(getApplicationContext(), "未发现SDCard", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(getApplicationContext(), "未授予权限！", Toast.LENGTH_LONG).show();
                        }

                    }
                });
            }

        }

        @Override
        public int getItemCount() {
            if (pictureFolder == null) {
                return 0;
            }
            return pictureFolder.getPictureList().size() + 1;
        }

        @Override
        public int getItemViewType(int position) {

            if (position == 0) {
                return 1;
            }
            return 2;

        }

    }

    private class MultiPictureAdapter extends RecyclerView.Adapter<MultiPictureAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {

            ImageView ivPicture;
            CheckBox cbCheck;

            public ViewHolder(View itemView) {
                super(itemView);
                ivPicture = itemView.findViewById(R.id.ivPicture);
                cbCheck = itemView.findViewById(R.id.cbCheck);
            }

        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(PicturePickerActivity.this).inflate(R.layout.view_item_picture_multi, parent, false);
            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
            final Picture picture = pictureFolder.getPictureList().get(position);

            Glide.with(PicturePickerActivity.this)
                    .load(picture.getPath()).apply(new RequestOptions()
                    .placeholder(R.mipmap.pp_placeholder)
                    .error(R.mipmap.pp_placeholder))
                    .into(holder.ivPicture);

            if (checkIsContains(picture)) {
                holder.cbCheck.setChecked(true);
            } else {
                holder.cbCheck.setChecked(false);
            }

            if (holder.cbCheck.isChecked()) {
                holder.ivPicture.setColorFilter(Color.parseColor("#80000000"), PorterDuff.Mode.SRC_ATOP);
            } else {
                holder.ivPicture.setColorFilter(Color.parseColor("#20000000"), PorterDuff.Mode.SRC_ATOP);
            }

            holder.cbCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (isChecked) {

                        if (selectPictureList.size() >= maxSelectNumber) {
                            buttonView.setChecked(false);
                            Toast.makeText(PicturePickerActivity.this, "最多选择" + maxSelectNumber + "张图片！", Toast.LENGTH_LONG).show();
                            return;
                        }
                        selectPictureList.add(picture);
                        holder.ivPicture.setColorFilter(Color.parseColor("#80000000"), PorterDuff.Mode.SRC_ATOP);
                    } else {
                        int selectIndex = searchPictureIndex(picture);
                        if (selectIndex != -1) {
                            selectPictureList.remove(selectIndex);
                        }
                        holder.ivPicture.setColorFilter(Color.parseColor("#20000000"), PorterDuff.Mode.SRC_ATOP);
                    }

                    int size = selectPictureList.size();
                    if (size > 0) {
                        tvComplete.setEnabled(true);
                        tvPreview.setEnabled(true);
                        tvComplete.setText("完成(" + size + "/" + maxSelectNumber + ")");
                        tvPreview.setText("预览(" + size + ")");
                    } else {
                        tvComplete.setEnabled(false);
                        tvPreview.setEnabled(false);
                        tvComplete.setText("完成");
                        tvPreview.setText("预览");
                    }

                }
            });

            holder.ivPicture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(PicturePickerActivity.this, PicturePreviewActivity.class);
                    intent.putExtra("pictureList", pictureFolder.getPictureList());
                    intent.putExtra("selectPictureList", selectPictureList);
                    intent.putExtra("maxSelectNumber", maxSelectNumber);
                    intent.putExtra("currentShowIndex", position);
                    startActivityForResult(intent, 3);

                }
            });


        }

        @Override
        public void onViewRecycled(ViewHolder holder) {
            super.onViewRecycled(holder);
            holder.cbCheck.setOnCheckedChangeListener(null);
        }

        @Override
        public int getItemCount() {
            if (pictureFolder == null) {
                return 0;
            }
            return pictureFolder.getPictureList().size();
        }

        private boolean checkIsContains(Picture picture) {
            boolean isCheck = false;
            for (Picture selectPicture : selectPictureList) {
                if (selectPicture.getPath().equals(picture.getPath())) {
                    isCheck = true;
                    break;
                }
            }
            return isCheck;
        }

        private int searchPictureIndex(Picture picture) {
            for (int i = 0; i < selectPictureList.size(); i++) {
                if (selectPictureList.get(i).getPath().equals(picture.getPath())) {
                    return i;
                }
            }
            return -1;
        }

    }

    private PictureFolder getPictureFolder(String path, List<PictureFolder> allFolders) {

        File imageFile = new File(path);
        File folderFile = imageFile.getParentFile();

        for (PictureFolder folder : allFolders) {
            if (folder.getName().equals(folderFile.getName())) {
                return folder;
            }
        }

        PictureFolder newFolder = new PictureFolder();
        newFolder.setName(folderFile.getName());
        newFolder.setPath(folderFile.getAbsolutePath());
        allFolders.add(newFolder);
        return newFolder;

    }

    // 文件夹按图片数量排序
    private void sortFolder(List<PictureFolder> pictureFolders) {
        Collections.sort(pictureFolders, new Comparator<PictureFolder>() {
            @Override
            public int compare(PictureFolder lhs, PictureFolder rhs) {
                if (lhs.getPictureList() == null || rhs.getPictureList() == null) {
                    return 0;
                }
                int lSize = lhs.getPictureList().size();
                int rSize = rhs.getPictureList().size();
                return lSize == rSize ? 0 : (lSize < rSize ? 1 : -1);
            }
        });
    }


    /**
     * 获取存放图片目录路径
     *
     * @return
     */
    protected String getTargetDirPath() {
        String targetDirPath = getExternalFilesDir("pictures").getPath();
        return targetDirPath;
    }

    /**
     * 获取应用名称
     *
     * @return
     */
    private String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

}
